package com.example.touch;

import java.net.InetAddress;

import android.annotation.SuppressLint;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.TaskStackBuilder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.nsd.NsdManager;
import android.net.nsd.NsdServiceInfo;
import android.net.nsd.NsdManager.ResolveListener;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;


public class NotificationService extends Service {

	private static final String TAG = "NotificationService";
	private NotificationCompat.Builder mBuilder;
	private NsdManager mNsdManager;
	private boolean isListening = false;
	
	
	@Override
	public void onCreate() {

		super.onCreate();
		
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
		registerReceiver(new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {

			    final String action = intent.getAction();
			    if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
			    	
			    	int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_ENABLED);
			    	
			        if (state == WifiManager.WIFI_STATE_ENABLED){
			        	
			        	if(isListening == false) {
						  mNsdManager.discoverServices("_http._tcp",
								  NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener);
						  isListening  = true;
			        	}
						
			        } else if (state == WifiManager.WIFI_STATE_DISABLED) {
			        	try {
			        	if(isListening  == true) {
			        		mNsdManager.stopServiceDiscovery(mDiscoveryListener);
			        		isListening  = false;
			        	}
			        	} catch(Exception ex) {
			        		// Ignore 
			        	}
			        }
			    }


			}
			
		}, intentFilter);
		
		mNsdManager = (NsdManager)getSystemService(NSD_SERVICE);
		  initializeDiscoveryListener(); 
		  initializeResolveListener();

	}

	private void OnServiceFound() {
		SendNotification();
	}
	
	
	private void SendNotification() {
		mBuilder =
		        new NotificationCompat.Builder(this)
		        .setSmallIcon(R.drawable.zero)
		        .setContentTitle("Indoor Positioning Available")
		        .setContentText("Click to open map!");
		Intent resultIntent = new Intent(this, TouchImageViewActivity.class);


		TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
		stackBuilder.addParentStack(TouchImageViewActivity.class);
		stackBuilder.addNextIntent(resultIntent);
		PendingIntent resultPendingIntent =
		        stackBuilder.getPendingIntent(
		            0,
		            PendingIntent.FLAG_UPDATE_CURRENT
		        );
		mBuilder.setContentIntent(resultPendingIntent);	
		
		pushNotification();
	}
	
	private void pushNotification()
	{
		NotificationManager mNotificationManager =
			    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		mNotificationManager.notify(1, mBuilder.build());
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}
	

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	};
	
	private NsdManager.DiscoveryListener mDiscoveryListener;
	private ResolveListener mResolveListener;
	private static String NSD_TAG = "NSDManager";
	private static String SERVICE_TYPE = "_http._tcp";
	private static String SERVICE_NAME = "MapServerv2";

	@SuppressLint("NewApi")
	public void initializeDiscoveryListener() {

		// Instantiate a new DiscoveryListener
		mDiscoveryListener = new NsdManager.DiscoveryListener() {

			// Called as soon as service discovery begins.
			@Override
			public void onDiscoveryStarted(String regType) {
				Log.d(NSD_TAG, "Service discovery started");
			}

			@Override
			public void onServiceFound(NsdServiceInfo service) {
				// A service was found! Do something with it.

				Log.d(NSD_TAG, "Service discovery success " + service);

				Log.d(NSD_TAG, "Service name: " + service.getServiceName());

				if (!service.getServiceType().startsWith(SERVICE_TYPE)) {
					// Service type is the string containing the protocol and
					// transport layer for this service.
					Log.d(NSD_TAG, "Unknown Service Type: " + service.getServiceType());
					Log.d(NSD_TAG, "Was looking for Type: " + SERVICE_TYPE);
				} else if (service.getServiceName().equals(SERVICE_NAME)) {
					Log.d(NSD_TAG, "Found it! Starting resolve...");
					mNsdManager.resolveService(service, mResolveListener);
					mNsdManager.stopServiceDiscovery(this);
					isListening = false;
				}
			}

			@Override
			public void onServiceLost(NsdServiceInfo service) {
				// When the network service is no longer available.
				// Internal bookkeeping code goes here.
				Log.e(NSD_TAG, "service lost" + service);
			}

			@Override
			public void onDiscoveryStopped(String serviceType) {
				Log.i(NSD_TAG, "Discovery stopped: " + serviceType);
			}

			@Override
			public void onStartDiscoveryFailed(String serviceType, int errorCode) {
				Log.e(NSD_TAG, "Discovery failed: Error code:" + errorCode);
				mNsdManager.stopServiceDiscovery(this);
			}

			@Override
			public void onStopDiscoveryFailed(String serviceType, int errorCode) {
				Log.e(NSD_TAG, "Discovery failed: Error code:" + errorCode);
				mNsdManager.stopServiceDiscovery(this);
			}

		};
	}

	public void initializeResolveListener() {
		mResolveListener = new NsdManager.ResolveListener() {

			private NsdServiceInfo mService;

			@Override
			public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) {
				// Called when the resolve fails. Use the error code to debug.
				Log.e(NSD_TAG, "Resolve failed for service: " + serviceInfo.getServiceName() + "Error code: " + errorCode);
			}

			@Override
			public void onServiceResolved(NsdServiceInfo serviceInfo) {
				Log.i(NSD_TAG, "Resolve Succeeded. " + serviceInfo);

				OnServiceFound();
				
				//NotificationService.this.InitializeWebServiceData();
			}
		};
	}

}
